package com.cn.wang.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cn.wang.entry.user;
import com.cn.wang.service.impl.UserServiceImpl;

@Controller
public class UserController {
	@Resource
	private UserServiceImpl userServiceImpl;
	
	@RequestMapping("/hello.htm")
	public ModelAndView getUser(HttpServletRequest request,HttpServletResponse response){
		Cookie cookie = new Cookie("name", "wang");
		response.addCookie(cookie);
		Cookie[] cookies =  request.getCookies();
		ModelAndView mView = new ModelAndView();
		String name = request.getParameter("name");
		List<user> userList = new ArrayList<user>();
		if(StringUtils.isNotBlank(name)){
			user user =  userServiceImpl.selectByName(name);
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>"+user.getEmail());
			mView.addObject("user", user);
		}else{
			 userList = userServiceImpl.selectAll();
		}
		mView.addObject("msg", "wangzaogen");
		mView.addObject("lists", userList);
		mView.setViewName("user");
		return mView;
		
	}
	
	@RequestMapping("/queryList.htm")
	@ResponseBody
	public Map<String, Object> queryUserList(HttpServletRequest request){
		Map<String,Object> result = new HashMap<String, Object>();
		List<user> userLists = userServiceImpl.selectAll();
		result.put("data", userLists);
		return result;
	}
	
	@RequestMapping("/login.htm")
	@ResponseBody
	public Map<String,Object> login(HttpServletRequest request ,user user){
		Map<String,Object> result = new HashMap<String, Object>();
		try {
			UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPassword());
			Subject currentUser = SecurityUtils.getSubject();  
            if (!currentUser.isAuthenticated()){
                //使用shiro来验证  
                currentUser.login(token);//验证角色和权限  
            } 
			result.put("status", 200);
			result.put("message", "登录成功");
		}catch (DisabledAccountException e) {
			result.put("status", 500);
			result.put("message", "帐号已经禁用。");
		} catch (Exception e) {
			result.put("status", 500);
			result.put("message", "帐号或密码错误");
		}
		return result;
	}
}
